<template>
    <div class="service-chat-container">
        <div class="chat-layout">
            <!-- 左侧订单详情 -->
            <div class="order-panel">
                <div class="panel-header">
                    <h3><i class="el-icon-document"></i> 订单详情</h3>
                </div>
                <div class="order-detail" v-if="orderDetail">
                    <div class="detail-item">
                        <span class="label">订单编号：</span>
                        <span>{{ orderDetail.recyclingOrderNum }}</span>
                    </div>
                    <div class="detail-item" v-if="orderDetail.appointmentTime">
                        <span class="label">预约时间：</span>
                        <span>{{ formatTime(orderDetail.appointmentTime) }}</span>
                    </div>
                    <div class="detail-item" v-if="orderDetail.createdAt">
                        <span class="label">创建时间：</span>
                        <span>{{ formatTime(orderDetail.createdAt) }}</span>
                    </div>
                    <div class="detail-item" v-if="orderDetail.appointPhone">
                        <span class="label">联系电话：</span>
                        <span>{{ orderDetail.appointPhone }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">回收地址：</span>
                        <span>{{ formatAddress(orderDetail) }}</span>
                    </div>
                    <div class="detail-item" v-if="orderDetail.status !== undefined">
                        <span class="label">订单状态：</span>
                        <span>{{ getOrderStatusText(orderDetail.status) }}</span>
                    </div>
                    <div class="detail-item" v-if="orderDetail.remarks">
                        <span class="label">备注信息：</span>
                        <span>{{ orderDetail.remarks }}</span>
                    </div>
                </div>
                <div v-else class="empty-detail">
                    <i class="el-icon-document"></i>
                    <p>暂无订单详情</p>
                </div>
            </div>

            <!-- 右侧聊天区域 -->
            <div class="chat-panel">
                <div class="panel-header">
                    <h3>
                        <i class="el-icon-service"></i> 
                        客服工作台
                        <el-tag size="small" type="warning" class="service-tag">客服模式</el-tag>
                        <el-button 
                            size="mini" 
                            type="text" 
                            icon="el-icon-refresh" 
                            @click="refreshChat"
                            :loading="refreshing"
                            class="refresh-btn"
                        >刷新</el-button>
                    </h3>
                </div>
                
                <div class="messages-container" ref="messageList">
                    <div v-for="msg in messages" 
                         :key="msg.time + msg.content + msg.senderType" 
                         :class="['message-item', getMessagePosition(msg)]">
                        <div class="message-time">{{ formatMessageTime(msg.time) }}</div>
                        <div class="message-content" :class="getMessageClass(msg)">
                            <div class="sender-info" v-if="msg.userId">
                                <i class="el-icon-user"></i> 用户消息
                            </div>
                            <div class="sender-info" v-else>
                                <i class="el-icon-service"></i> 客服回复
                            </div>
                            {{ msg.content }}
                        </div>
                    </div>
                </div>

                <div class="input-area">
                    <el-input 
                        v-model="newMessage"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入客服回复..."
                        resize="none"
                        @keyup.enter.native="sendMessage"
                    ></el-input>
                    <el-button 
                        type="warning"
                        icon="el-icon-s-promotion"
                        @click="sendMessage"
                        :loading="sending"
                    >发送回复</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import mqtt from 'mqtt'

export default {
    name: 'ServiceChat',
    data() {
        return {
            orderNum: '',
            orderDetail: null,
            messages: [],
            newMessage: '',
            sending: false,
            client: null,
            refreshing: false,
            refreshInterval: null,
            mqttTopic: '' // 新增MQTT主题变量
        }
    },
    created() {
        // 从路由参数或本地存储获取订单号
        this.orderNum = this.$route.query.orderNum || localStorage.getItem('currentChatOrder')
        
        console.log('当前订单号:', this.orderNum)
        
        if (this.orderNum) {
            // 设置MQTT主题
            this.mqttTopic = `chat/${this.orderNum}`
            
            // 先获取订单详情
            this.fetchOrderDetail()
            // 然后获取聊天记录
            this.fetchChatHistory()
            // 最后初始化MQTT连接
            this.initMqttConnection()
            
            // 将刷新间隔改为更长时间，因为现在主要依赖MQTT实时更新
            this.refreshInterval = setInterval(() => {
                console.log('定时刷新聊天记录')
                this.fetchChatHistory()
            }, 30000) // 改为30秒
        } else {
            this.$message.warning('未找到订单信息')
            this.$router.push('/station/orders')
        }
    },
    beforeDestroy() {
        // 清除定时器
        if (this.refreshInterval) {
            clearInterval(this.refreshInterval)
        }
        
        // 断开MQTT连接
        if (this.client) {
            this.client.unsubscribe(this.mqttTopic)
            this.client.end()
            console.log('MQTT连接已断开')
        }
    },
    methods: {
        async fetchOrderDetail() {
            try {
                const response = await this.$http.post('/recycle/recyclingOrder/selectOrderByCondition', {
                    recyclingOrderNum: this.orderNum
                })
                if (response.data.code === 200) {
                    // 从返回的列表中获取第一个订单作为当前订单详情
                    if (response.data.data && response.data.data.list && response.data.data.list.length > 0) {
                        this.orderDetail = response.data.data.list[0]
                        console.log('获取到订单详情:', this.orderDetail)
                    } else {
                        console.error('未找到订单详情')
                        this.$message.warning('未找到订单详情')
                    }
                }
            } catch (error) {
                console.error('获取订单详情失败:', error)
                this.$message.error('获取订单详情失败')
            }
        },
        async fetchChatHistory() {
            try {
                console.log('获取聊天记录，订单号:', this.orderNum)
                const response = await this.$http.get('/userService/user/selectChatHistory', {
                    params: {
                        recyclingOrderNum: this.orderNum,
                        userId: 0  // 客服端查询
                    }
                })
                
                if (response.data.code === 200) {
                    console.log('聊天记录原始数据:', response.data.data)
                    
                    // 确保数据是数组
                    if (Array.isArray(response.data.data)) {
                        // 处理每条消息
                        const newMessages = response.data.data.map(msg => {
                            // 如果消息是字符串，尝试解析为JSON
                            if (typeof msg === 'string') {
                                try {
                                    return JSON.parse(msg)
                                } catch (e) {
                                    console.error('解析消息失败:', e, msg)
                                    return null
                                }
                            }
                            return msg
                        }).filter(msg => msg !== null) // 过滤掉解析失败的消息

                        // 去重处理
                        const uniqueMessages = [];
                        const messageMap = new Map();
                        
                        newMessages.forEach(msg => {
                            // 使用内容和时间作为唯一标识
                            const key = `${msg.content}_${msg.time}`;
                            if (!messageMap.has(key)) {
                                messageMap.set(key, true);
                                uniqueMessages.push(msg);
                            }
                        });

                        // 更新消息列表,按时间排序
                        this.messages = uniqueMessages.sort((a, b) => new Date(a.time) - new Date(b.time))
                        
                        console.log('处理后的消息列表:', this.messages)
                    } else {
                        console.error('聊天记录数据格式错误:', response.data.data)
                    }
                    
                    this.$nextTick(() => {
                        this.scrollToBottom()
                    })
                } else {
                    this.$message.error(response.data.message || '获取聊天记录失败')
                }
            } catch (error) {
                console.error('获取聊天记录失败:', error)
                this.$message.error('获取聊天记录失败')
            }
        },
        initMqttConnection() {
            if (!this.orderNum) return
            
            const clientId = 'service_' + Math.random().toString(16).substr(2, 8)
            const url = 'ws://127.0.0.1/mqtt'
            const options = {
                port: 8083,
                keepalive: 60,
                clientId: clientId,
                protocolId: 'MQTT',
                protocolVersion: 4,
                clean: true,
                connectTimeout: 30 * 1000,
                will: {
                    topic: 'chat',
                    payload: '客服断开连接',
                    qos: 0,
                    retain: false
                }
            }

            // 创建MQTT连接
            this.client = mqtt.connect(url, options)
            
            // 连接成功后订阅聊天主题
            this.client.on('connect', () => {
                console.log('MQTT连接成功')
                // 订阅该订单的聊天主题
                const topic = `chat/${this.orderNum}`
                this.client.subscribe(topic, { qos: 0 }, (error) => {
                    if (!error) {
                        console.log(`成功订阅聊天主题: ${topic}`)
                    } else {
                        console.error(`订阅聊天主题失败: ${error}`)
                    }
                })
            })
            
            // 接收消息
            this.client.on('message', (topic, payload) => {
                try {
                    const msg = JSON.parse(payload.toString())
                    console.log('收到MQTT消息:', msg)
                    
                    // 检查是否是当前订单的消息
                    if (msg.recyclingOrderNum === this.orderNum) {
                        // 改进重复消息检测逻辑
                        const isDuplicate = this.messages.some(existingMsg => 
                            (existingMsg.time === msg.time && existingMsg.content === msg.content) ||
                            (existingMsg.content === msg.content && 
                             Math.abs(new Date(existingMsg.time) - new Date(msg.time)) < 5000) // 5秒内相同内容视为重复
                        )
                        
                        if (!isDuplicate) {
                            // 添加新消息
                            this.messages.push(msg)
                            this.scrollToBottom()
                            
                            // 如果是用户消息，显示通知
                            if (msg.userId) {
                                this.$notify({
                                    title: '新消息',
                                    message: msg.content,
                                    type: 'success',
                                    duration: 3000
                                })
                            }
                        } else {
                            console.log('检测到重复消息，已忽略')
                        }
                    }
                } catch (error) {
                    console.error('解析消息失败:', error)
                }
            })
        },
        async sendMessage() {
            if (!this.newMessage.trim()) {
                this.$message.warning('请输入消息内容')
                return
            }
            
            const messageContent = this.newMessage.trim()
            this.newMessage = '' // 立即清空输入框
            
            // 创建临时消息对象
            const tempId = 'temp_' + Date.now()
            const localMessage = {
                recyclingOrderNum: this.orderNum,
                content: messageContent,
                senderType: 'service',
                time: new Date().toISOString(),
                _temp: true,
                _tempId: tempId
            }
            
            this.scrollToBottom()
            
            // 发送到服务器
            try {
                const response = await this.$http.post('/platform/account/chat', {
                    recyclingOrderNum: this.orderNum,
                    content: messageContent,
                    senderType: 'service'
                })
                
                if (response.data.code !== 200) {
                    // 发送失败，显示错误
                    this.$message.error(response.data.message || '发送失败')
                    
                    // 从消息列表中移除临时消息
                    this.messages = this.messages.filter(msg => msg._tempId !== tempId)
                    
                    // 恢复消息内容
                    this.newMessage = messageContent
                }
            } catch (error) {
                console.error('发送消息错误:', error)
                this.$message.error('发送失败，请重试')
                
                // 从消息列表中移除临时消息
                this.messages = this.messages.filter(msg => msg._tempId !== tempId)
                
                // 恢复消息内容
                this.newMessage = messageContent
            }
        },
        getMessagePosition(msg) {
            return msg.userId || msg.senderType === 'user' ? 'message-left' : 'message-right'
        },
        getMessageClass(msg) {
            return msg.senderType === 'service' || (!msg.userId && !msg.senderType) ? 'service' : 'user'
        },
        formatTime(time) {
            if (!time) return '未设置'
            return new Date(time).toLocaleString()
        },
        formatAddress(order) {
            return [order.city, order.district, order.street]
                .filter(Boolean)
                .join(' ')
        },
        formatMessageTime(timeStr) {
            if (!timeStr) return '未知时间'
            
            try {
                const date = new Date(timeStr)
                if (isNaN(date.getTime())) {
                    return timeStr
                }
                
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                })
            } catch (error) {
                console.error('格式化日期出错:', error)
                return timeStr
            }
        },
        scrollToBottom() {
            this.$nextTick(() => {
                if (this.$refs.messageList) {
                    this.$refs.messageList.scrollTop = this.$refs.messageList.scrollHeight
                }
            })
        },
        async refreshChat() {
            this.refreshing = true
            try {
                await this.fetchChatHistory()
                this.$message.success('聊天记录已刷新')
            } catch (error) {
                console.error('刷新聊天记录失败:', error)
            } finally {
                this.refreshing = false
            }
        },
        getOrderStatusText(status) {
            const statusMap = {
                0: '待接单',
                1: '已接单',
                2: '已完成',
                3: '已取消'
            }
            return statusMap[status] || '未知状态'
        }
    }
}
</script>

<style scoped>
.service-chat-container {
    height: 100vh;
    padding: 20px;
    background-color: #f0f9eb;
}

.chat-layout {
    display: grid;
    grid-template-columns: 300px 1fr;
    gap: 20px;
    height: calc(100vh - 40px);
    background: white;
    border-radius: 8px;
    overflow: hidden;
}

.panel-header {
    padding: 15px;
    background: #f0f9eb;
    border-bottom: 1px solid #e0e0e0;
}

.panel-header h3 {
    margin: 0;
    color: #67c23a;
    display: flex;
    align-items: center;
    gap: 8px;
}

.service-tag {
    margin-left: auto;
}

.order-panel {
    background: white;
    border-right: 1px solid #e0e0e0;
    display: flex;
    flex-direction: column;
}

.order-detail {
    padding: 20px;
    flex: 1;
    overflow-y: auto;
}

.detail-item {
    margin-bottom: 15px;
}

.detail-item .label {
    color: #909399;
    margin-right: 8px;
}

.chat-panel {
    display: flex;
    flex-direction: column;
    background: white;
}

.messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f8f8f8;
    max-height: calc(100vh - 200px); /* 限制最大高度 */
}

.message-item {
    margin-bottom: 20px;
}

.message-left {
    text-align: left;
}

.message-right {
    text-align: right;
}

.message-content {
    display: inline-block;
    max-width: 70%;
    padding: 12px;
    border-radius: 8px;
    position: relative;
    word-break: break-word; /* 确保长文本会换行 */
    white-space: pre-wrap; /* 保留空格和换行 */
}

.message-content.service {
    background: #ffd04b;
    color: #303133;
    border-radius: 8px 8px 8px 0;
}

.message-content.user {
    background: #67c23a;
    color: white;
    border-radius: 8px 8px 0 8px;
}

.sender-info {
    font-size: 12px;
    margin-bottom: 4px;
    opacity: 0.8;
}

.message-time {
    font-size: 12px;
    color: #909399;
    margin: 5px 0;
}

.input-area {
    padding: 20px;
    background: white;
    border-top: 1px solid #e0e0e0;
    display: flex;
    gap: 10px;
}

.input-area .el-button {
    height: 82px;
    width: 100px;
}

.empty-detail {
    text-align: center;
    padding: 40px 20px;
    color: #909399;
}

.empty-detail i {
    font-size: 48px;
    margin-bottom: 10px;
}

.refresh-btn {
    margin-left: 10px;
    color: #67c23a;
}
</style> 